#include "StdAfx.h"
#include "StateManager.h"
#include "BaseState.h"
#include "Game.h"

StateManager::StateManager(void)
{
}

StateManager::~StateManager(void)
{
}

void StateManager::Shutdown()
{
	for (vector<BaseState*>::iterator i = currentStates.begin(); i != currentStates.end(); ++i)
	{
		(*i)->Shutdown();
	}
	currentStates.clear();
}

void StateManager::ChangeState(BaseState* _state, bool _whipe)
{
	if (_whipe)
	{
		for (vector<BaseState*>::iterator i = currentStates.begin(); i != currentStates.end(); ++i)
		{
			if(*i)
				(*i)->Shutdown();
		}
		currentStates.clear();
		currentStates.push_back(_state);
	}
	else
	{
		if(currentStates.back())
			currentStates.back()->Shutdown();
		currentStates.back() = _state;
	}

	_state->Init();
}

void StateManager::Push(BaseState* _state)
{
	currentStates.push_back(_state);
	_state->Init();
}

void StateManager::Pop()
{
	if (currentStates.size() == 0)
		return;

	currentStates.back()->Shutdown();
	currentStates.pop_back();

	if (!currentStates.size())
	{
		PostMessage(Game::GetInstance()->GetWindow(), WM_QUIT, 0, 0);
	}
}

void StateManager::Update(float _dt)
{
	if (currentStates.size() == 0)
		return;

	currentStates.back()->Update(_dt);
}

void StateManager::Render()
{
	if (currentStates.size() == 0)
		return;

	currentStates.back()->Render();
}

bool StateManager::IsStateActive(const BaseState* _state)
{
	for (vector<BaseState*>::iterator i = currentStates.begin(); i != currentStates.end(); ++i)
	{
		if ((*i) == _state)
			return true;
	}

	return false;
}

DECLARE_SINGLETON_CPP(StateManager);